// 创建vite步骤
// 初始化创建 vite + vue 项目，执行 yarn create vite xxx
// 通过安装插件(yarn add unplugin-vue-components)启用 element plus 自动按需引入功能，可以减少打包生成文件的总大小
// 通过安装插件(yarn add unplugin-auto-import)启用 vue 自动引入功能，可以不用再写 import { ref, reactive }
// 配置@符号
// 通过 yarn add vue-router 安装并启用路由功能
// 通过 yarn add axios  增加 axios支持，并在 vite.config.js 内设置开发服务器支持
// 通过 yarn add vuex 增加vuex支持
// 通过 yarn add less 增加css预处理器less支持
// 调整生成的临时文件(*.d.ts)路径，并将其加入 .gitignore
// 更新 readme，增加项目初始化、启动调试、打包的命令

// 封装axios
{
	import axios from "axios";
	const BASE_URL_API = process.env.NODE_ENV !== 'production' ? '/local' : '/gateway'
	const service = axios.create({
		baseURL: BASE_URL_API,
		timeout: 30000,
	});
	service.interceptors.request.use(function (config) {
		// 在发送请求之前做些什么
		config.headers['Authorization'] = `Bearer ${localStorage.token}`
		return config;
	}, function (error) {
		// 对请求错误做些什么
		return Promise.reject(error);
	});
	service.interceptors.response.use(function (response) {
		// 2xx 范围内的状态码都会触发该函数。
		// 对响应数据做点什么
		return response;
	}, function (error) {
		// 超出 2xx 范围的状态码都会触发该函数。
		// 对响应错误做点什么
		return Promise.reject(error);
	});
	export default service
}
// vuex index.js 配置
{
	import Vuex from 'vuex'
	const modules = {}
	const files = import.meta.globEager("./modules/*.js")
	for (const key in files) {
	  const value = files[key]
	  const moduleName = key.replace(/^\.\/(.*)\.\w+$/, '$1')
	  modules[moduleName] = value.default
	}
	const store = new Vuex.Store({
	  modules,
	})
	export default store
}
//vuex module/..js
{
	const state = {}
	const mutations = {}
	const actions = {}
	export default {
		// namespaced: true,
		state,
		mutations,
		actions
	}
}
//路由配置
{
	import { createRouter, createWebHashHistory } from 'vue-router'

	export const constantRoutes = [
	  {
		path: '/',
		name: 'Common',
		component: () => import('@/views/Common.vue'),
		redirect: '/playerList',
		children: []
	  },
	  {
		path: '/login',
		name: 'Login',
		meta: { title: '登录页面' },
		component: () => import('@/views/Login.vue'),
	  },
	]

	export const router = createRouter({
	  history: createWebHashHistory(),
	  routes: constantRoutes
	})
	router.beforeEach(async(to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})
}
// 封装 处理路由表
{
	const modules = import.meta.glob("../views/**/**.vue");
	const page404 = () => import("../views/404.vue")
	const Container = () => import('../views/Container.vue')

	/**
	 * {
			path: '/MeteorologicalProducts',
			name: '气象产品',
			// component: () => import('@/views/Common.vue'),
			meta: {
				name: '气象产品',
				// 侧边栏
				sidebar: [
					{ path: 'forecast7Days', name: '七天预报查询', file: 'forecast7Days', meta: {} },
					{ path: 'scenicSpots', name: '景点天气查询', file: 'scenicSpots', meta: {}, childrenList: [
						{ path: 'scenicSpots/forecast', name: '景点预报查询', file: 'forecast', meta: {}, childrenList: [
							{ path: 'scenicSpots/forecast/fore-7', name: '7天预报查询', file: 'scenicSpotsForecast7', meta: {} }, 
							{ path: 'scenicSpots/forecast/fore-24', name: '24小时预报', file: 'scenicSpotsForecast24', meta: {} },
						]},
						{ path: 'scenicSpots/scenicSpotsLive', name: '景点实况查询', file: 'scenicSpotsLive', meta: {} },
					] },
				],
				// 详情页
				detail: [
					
				]
			},
		}
	 * 
	 * 
	 */
	// 查找侧边栏是否有下一级菜单
	const itemList = []
	const children_list = (item, url) => {
	  item.forEach((ele) => {
		if (ele.childrenList?.length > 0) {
		  children_list(ele.childrenList)
		} else {
		  itemList.push(ele)
		}
	  })
	  return itemList
	}
	// 添加到父级路由
	const addParent = (item_child, item) => {
	  item_child.path = `${item.path}/${item_child.path}`
	  const file = `../views${item.path}/${item_child.file}.vue`
	  item.children.push({
		path: item_child.path,
		name: item_child.name,
		component: modules[file] || page404,
		meta: item_child.meta,
		children: []
	  })
	}
	// 处理sidebar和detail
	export const routerList = (route) => {
	  route[0].children.forEach((item) => {
		itemList.length = 0
		item.children = []
		if (!item.component) {
		  item.component = Container
		}
		if (item.meta.sidebar?.length > 0) {
		  item.meta.sidebar.forEach(async (item_child) => {
			if (item_child.childrenList?.length > 0) {
			  await children_list(item_child.childrenList, item.path)  
			} else {
			  itemList.push(item_child)
			}
		  })
		  itemList.forEach((item_child) => {
			addParent(item_child,item)
		  })
		}
		if (item.meta.detail?.length > 0) {
		  item.meta.detail.forEach((item_child) => {
			if (!item_child.parent) {
			  addParent(item_child,item)
			} else {
			  item.children.forEach((ele_parent) => {
				if (item_child.parent == ele_parent.name) {
				  addParent(item_child, ele_parent)
				}
			  })
			}
		  })
		  item.children.find((ele, index) => {
			if (ele.children?.length > 0) {
			  ele.redirect = ele.children[0].path
			}
		  })
		}
		if (item.children.length !== 0) {
		  item.redirect = item.children[0].path
		}
	  })

	  route[0].redirect = route[0].children[0].path
	  // console.log(route);
	  return route
	}
}

// vite.config.js 配置 
// 设置代理 配置@符号 element按需引入 vite自动引入
{
	import { defineConfig } from 'vite'
	import vue from '@vitejs/plugin-vue'
	import AutoImport from 'unplugin-auto-import/vite'
	import Components from 'unplugin-vue-components/vite'
	import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
	import { resolve } from "path"


	export default defineConfig({
	  plugins: [
		vue(),
		AutoImport({
		  imports: ['vue'],
		  resolvers: [ElementPlusResolver()],
		}),
		Components({
		  resolvers: [ElementPlusResolver()],
		}),
	  ],
	  resolve: {
		alias: {
		  "@": resolve(__dirname, "src")
		}
	  },
	  server: {
		port: '3009',
		host: true,
		open: true,
		proxy: {
		  '/api/': {
			target: 'http://gateway.weather.hywea.cn:30080',
			changeOrigin: true,
			rewrite: (path) => path.replace(/^\/api/, ''),
		  },
		  '/api2/': {
			target: 'http://192.168.1.185:6080',
			changeOrigin: true,
			rewrite: (path) => path.replace(/^\/api2/, ''),
		  }
		}
	  }
	})
}